package jeu;
import java.io.*;
import java.net.*;
import java.util.Scanner;

import messages.*;

public class Client {
	private Socket socket;
	private int port;
	private String ip;
	ObjectInputStream ois;
	ObjectOutputStream oos;
	
	private int id;
	
	public Client(String ip_, int port_) throws Exception {
		id = -1;
		ip = ip_;
		port = port_;
		socket = new Socket(ip, port);
		ois = new ObjectInputStream(socket.getInputStream());
		oos = new ObjectOutputStream(socket.getOutputStream());
	}
	
	public void run() throws Exception {
		//Receive a message from the server
		Object o = ois.readObject();

		//Check the type of the message
		if (o instanceof ConnectionMessage) {
			ConnectionMessage im = (ConnectionMessage) o;
			id = im.getId();
			System.out.print("The client id is: " + id);
		} else if (o instanceof DemandeQuiPrendMessage) {
			//Demander au client s'il veut prendre la carte 
			oos.writeObject(new ReponseQuiPrendMessage(true,0));
		}

		ois.close();

		//Keep the client running to test the response 
		//of the server to multiple clients
		while (true) {
			Scanner scanner = new Scanner(System.in);
			int option = scanner.nextInt();
			if (option == 0) {
				oos.writeObject(new ExitMessage(id));
				socket.close();
			}
		}
	}

	public static void main(String[] args) {
		try {
			Client client = new Client("127.0.0.1", 1234);
			client.run();
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
}
